package org.carota.itext5;

import cn.hutool.core.lang.UUID;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.converter.pdf.PdfConverter;
import org.apache.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.carota.pdf.PdfProcessor;
import org.carota.util.RelateUtil;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * @author : AnWen
 * @version :1.0
 * @email : anwen375@qq.com
 * @since : 2023-03-31 17:22
 */
@Slf4j
@NoArgsConstructor
public class FillDocxTemplateConfigurer extends FillPdfTemplateConfigurer {


    public FillDocxTemplateConfigurer(PdfProcessor processor) {
        super (processor);
    }

    /**
     * 执行PDF操作
     */
    @Override
    public void execute() {

        String templatePath = processor.getTemplatePath ();
        ByteArrayOutputStream bos = processor.getBos ();

        try (InputStream inputStream = RelateUtil.getInputStream (templatePath)) {
            XWPFDocument docx = new XWPFDocument (inputStream);
            paragraphReplace (docx.getParagraphs (), getData ());
            PdfOptions options = PdfOptions.create ();
            PdfConverter.getInstance ().convert (docx, bos, options);
        } catch (Exception e) {
            log.error ("文件转化异常:", e);
        }

    }


    private void paragraphReplace(List<XWPFParagraph> paragraphs, Map<String, Object> params) {
        for (XWPFParagraph p : paragraphs) {
            for (XWPFRun r : p.getRuns ()) {
                String content = r.getText (r.getTextPosition ());
//                System.out.println (content);
                if (params.containsKey (content)) {
                    Object obj = params.get (content);
                    if (obj instanceof InputStream) {
                        try {
                            r.setText ("", 0);
                            r.addPicture ((InputStream) params.get (content), XWPFDocument.PICTURE_TYPE_PNG, UUID.fastUUID ().toString (), Units.toEMU (75), Units.toEMU (75));
                        } catch (InvalidFormatException | IOException e) {
                            log.error ("插入图片失败: ", e);
                        }
                    } else {
                        r.setText (obj.toString (), 0);
                    }
                }
            }
        }
    }


    /**
     * 校验参数
     */
    @Override
    protected void checkParams() {
        checkParams ("word模板填充", getData (), "data");
    }


    @Override
    public int getOrder() {
        return HIGHEST_PRECEDENCE;
    }
}
